package fr.inserm.u915.organifooyi.controlers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
import javax.servlet.ServletException;
import fr.inserm.u915.organifooyi.web.Message;
import fr.inserm.u915.organifooyi.web.RequestHandler;

public abstract class AbstractHandler extends RequestHandler
	{
	private EntityManager entityManager=null;
	protected AbstractHandler()
		{
		entityManager=null;
		}
	
	protected EntityManagerFactory getEntityManagerFactory()
		{
		EntityManagerFactory emf = (EntityManagerFactory)getRequest().getServletContext().getAttribute("emf");
		if(emf==null) throw new NullPointerException();
		return emf;
		}
	
	public EntityManager getEntityManager()
		{
		if(entityManager==null)
			{
			entityManager=getEntityManagerFactory().createEntityManager();
			entityManager.setFlushMode(FlushModeType.COMMIT);
			}
		return entityManager;
		}
	
	public boolean containsErrorMessages()
		{
		@SuppressWarnings("unchecked")
		List<Message> messages=(List<Message>)getRequest().getAttribute("messages");
		if(messages==null) return false;
		for(Message msg:messages) if(msg.getLevel()==Message.Level.error) return true;
		return false;
		}
	
	protected void addMessage(Message msg)
		{
		@SuppressWarnings("unchecked")
		List<Message> messages=(List<Message>)getRequest().getAttribute("messages");
		if(messages==null)
			{
			messages=new ArrayList<Message>();
			getRequest().setAttribute("messages",messages);
			}
		messages.add(msg);
		}
	public void addErrorMessage(String text)
		{
		addMessage(new Message(text,Message.Level.error));
		}
	
	public void addMessage(Throwable err)
		{
		addErrorMessage(err.getMessage());
		}
	
	
	public void addWarningMessage(String text)
		{
		addMessage(new Message(text,Message.Level.warning));
		}
	public void addPlainMessage(String text)
		{
		addMessage(new Message(text,Message.Level.message));
		}
	public void addSuccessMessage(String text)
		{
		addMessage(new Message(text,Message.Level.message));
		}
	
	public void addLogMessage(Object text)
		{
		if(isUserAdmin()) addMessage(new Message(String.valueOf(text),Message.Level.log));
		}


	
	protected boolean isUserCanWrite()
		{
		return getRequest().isUserInRole("ROLE_USER");
		}
	
	protected boolean isUserAdmin()
		{
		return getRequest().isUserInRole("ROLE_ADMIN") ||
				isUserCanWrite()//TODO remove
				;
		}

	
	protected boolean verifyUserCanWrite()
		{
		if(!isUserCanWrite())
			{
			addErrorMessage("No credential to update the database");
			return false;
			}
		return true;
		}
	
	@Override
	public void close()
		{
		if(entityManager!=null)
			{
			entityManager.clear();
			entityManager.close();
			entityManager=null;
			}
		super.close();
		}
	
	@Override
	public int service() throws IOException,ServletException
		{
		return 0;
		}
	}
